#!/bin/sh
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
if [ -z "$LMD_DATA_ROOT" ]; then
    echo "Error: Env LMD_DATA_ROOT is not defined."
    exit 1
else
    echo "Env LMD_DATA_ROOT: $LMD_DATA_ROOT"
fi

# if [ ! -n "{$SEVEN_Z_DIR:-}" ]; then
    SEVEN_Z_DIR="${LMD_DATA_ROOT}/scripts/global-tools/7z"
#     echo 'SEVEN_Z_DIR is empty. set default value.'$SEVEN_Z_DIR
# fi

mkdir -p $SEVEN_Z_DIR
if [ -d "$SEVEN_Z_DIR" ]; then
    echo "7z Dir: "$SEVEN_Z_DIR
else
    echo "Error, 7z Dir dose not exist, please retry. "$SEVEN_Z_DIR
    exit 1
fi

cd $SEVEN_Z_DIR

function install_7z {
    if [ -f /etc/os-release ]; then
        echo "Linux system."
        echo "Not yet support."
    elif [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
        echo "macOS system."
        ARCH=$(uname -m)
        echo "do not need 7z."
    elif current_os_is_windows; then
        echo "Windows system."
        # INSTALLER_7Z_URL='https://www.7-zip.org/a/7zr.exe'
        INSTALLER_7Z_URL='https://d-1314735556.cos.ap-shanghai.myqcloud.com/pkgs/tools/7zr.exe'
        DOWNLOAD_FILE_NAME_7Z=7zr.exe
        download_file_7z
        
        echo "set 7zr var""$SEVEN_Z_DIR/7zr.exe"
        alias 7zr="$SEVEN_Z_DIR/7zr.exe"
        
        # add 7z dir to PATH
        export PATH=$PATH:"${SEVEN_Z_DIR}/"
    else
        echo "Unknown OS"
    fi
}

function download_file_7z {
    echo "start download ${INSTALLER_7Z_URL}"
    curl --ssl-no-revoke -L -C - --retry 7 -o "$DOWNLOAD_FILE_NAME_7Z" $INSTALLER_7Z_URL
    # curl: (56) HTTP server doesn't seem to support byte ranges. Cannot resume.
    exit_code=$?
    if [ $exit_code -eq 56 ]; then
        rm -f ./$DOWNLOAD_FILE_NAME_7Z
        echo "retry download without byte ranges"
        curl --ssl-no-revoke -L --retry 7 -o "$DOWNLOAD_FILE_NAME_7Z" $INSTALLER_7Z_URL
    fi
    echo "download ok."
}

install_7z
